import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

import {useCounterStore} from '@/stores/counter'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'Login',
      component:() => import('../views/HomeView.vue'),
      meta:{
        requireAuth:true
      }
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue'),
    },
    {
      path: '/MenuView',
      name: 'MenuView',
      component: () => import('../views/MenuView.vue'),
      children:[
        {
          path: '/AddnewUser',
          name: 'AddnewUser',
          component: () => import('../views/RollBoaAC/AddnewUser.vue'),
        },
        {
          path: '/AddRoleOrPermissions',
          name: 'AddRoleOrPermissions',
          component: () => import('../views/RollBoaAC/AddRoleOrPermissions.vue'),
        },
        {
          path: '/GetTraceablyView',
          name: 'GetTraceablyView',
          component: () => import('../views/Traceability/GetTraceablyView.vue'),
        },
        {
          path: '/GetCultivationList',
          name: 'GetCultivationList',
          component: () => import('../views/Cultivations/GetCultivationList.vue'),
        },
      ]
    },
  ],
})



//全局路由守卫
router.beforeEach((to:any,from:any,next)=>{
  console.log(to);
  console.log(from);
  const counterStore=useCounterStore();
  if(to.name=='Login')
  {
    next()
  }
  else
  {
    if(counterStore.userinfo)
    {
      next()
    }
    else{
      next({name:'Login'})
    }
  }
  if (to.meta.requireAuth) {  // 判断该路由是否需要登录权限
    if (localStorage.token) {  // 获取当前的token是否存在
      console.log("token存在");
      next();
    } else {
      console.log("token不存在");
      next({
        path: '/Login', // 将跳转的路由path作为参数，登录成功后跳转到该路由
        query: {redirect: to.fullPath}
      })
    }
  }
  else { // 如果不需要权限校验，直接进入路由界面
    next();
  }
});
  

export default router
